package com.ti.ouxun.util.adapter;

import android.util.Log;

public class ReflectObjectFieldsValue {
	
	private static final String TAG = "ReflectObjectFieldsValue";
	
	/**
	 * 利用反射机制调用所有要取值的字段名对应的 getXXX() 方法来取值
	 * @param instance
	 * @return 
	 */
	public static Object[] getFieldsValue(Object instance, String[] fieldsName) {
		int size = fieldsName.length;
		Object[] fieldsValue = new Object[size];
		for( int i=0; i<size; i++ ) {
			fieldsValue[i] = getFieldValue(instance, fieldsName[i]);
		}
		return fieldsValue;
	}
	
	/**
	 * 得到
	 * @param instance
	 * @param field
	 * @return
	 */
	public static Object getFieldValue(Object instance, String fieldName) {
		String getMethodName = "get" + toUpperCaseFirstLetter(fieldName);
		Object fieldValue = null;
		try {
			fieldValue = instance.getClass().getMethod(getMethodName).invoke(instance);
		} catch (Exception e) {
			Log.e(TAG, instance.getClass().getName() + " 中没有 " + getMethodName + "()" + "方法");
			e.printStackTrace();
		}
		return fieldValue;
	}
	
	/**
	 * 将字符串首字母大写
	 * @param str
	 * @return
	 */
	private static String toUpperCaseFirstLetter(String str) {
		char[] array = str.toCharArray();
		if( ! Character.isUpperCase(array[0]) ) {
			array[0] = Character.toUpperCase(array[0]);
		}
		return new String(array);
	}
}
